package com.hzqy.web.ac;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hzqy.commons.utils.FileType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.ConstantUtils;
import com.hzqy.commons.utils.ExcelUtil;
import com.hzqy.commons.utils.ExcelUtil.MyEntry;
import com.hzqy.service.special.SpecialServiceBean;
import com.hzqy.web.vo.PmsUserVo;
import com.hzqy.web.vo.SysProductVo;
import com.hzqy.web.vo.special.SpecialInfoVo;
import com.hzqy.web.vo.special.SpecialViewVo;

import static com.hzqy.commons.utils.FileUtil.fileCheck;

@Controller
@RequestMapping("/")
public class SpecialAction {
	protected final Logger LOG=LoggerFactory.getLogger(getClass());
	private static final String[] allowedFileType = new String[]{"png", "jpg", "gif","zip","jar","tar","docx","doc","xlsx","xls","flv","mp4","mp3","mpg","avi","mov","wmv"};
	@Resource
	private SpecialServiceBean specialServiceBean;

	@RequestMapping("/special/specialViewDataUpdate")
	@ResponseBody
	public Object specialViewDataUpdate(String json){
		try {
			Base64.Decoder decoder = Base64.getDecoder();
			byte[] bytes = decoder.decode(json);
			json = new String(bytes, "UTF-8");
		}catch (Exception e) {
			LOG.debug("specialViewDataUpdate-json无需转码");
		}
		Map<String,Object> resultMap = new HashMap<String,Object>();
		LOG.debug("specialViewDataUpdate-json:"+json);
		JSONObject jsonObject=JSONObject.parseObject(json);
		int flag = specialServiceBean.specialViewDataUpdate(jsonObject);
		if(flag > 0) {
			resultMap.put("success", true);
			resultMap.put("result","修改专辑内容成功!");
		} else {
			resultMap.put("success", true);
			resultMap.put("result","修改专辑内容失败!flag="+flag);
		}
		return resultMap;
	}
	@RequestMapping("/special/specialViewInfo")
	@ResponseBody
	public Object specialViewInfo(String json,HttpServletResponse response){
		JSONObject jsonObject=JSONObject.parseObject(json);
		List<SpecialViewVo> buttonlist=specialServiceBean.selctSpecialViewList(jsonObject.getString("specialid"));
		return buttonlist;
	}


	@RequestMapping("/special/insert_special")
	@ResponseBody
	public Object insertSpecial(SpecialInfoVo specialInfoVo){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = specialServiceBean.insertSpecial(specialInfoVo);
		if(flag > 0) {
			resultMap.put("success", true);
			resultMap.put("result","新增内容成功!");
		} else {
			resultMap.put("success", true);
			resultMap.put("result","新增内容失败!flag="+flag);
		}
		return resultMap;
	}

	@RequestMapping("/special/update_special")
	@ResponseBody
	public Object updateSpecial(SpecialInfoVo specialInfoVo){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = specialServiceBean.updateSpecial(specialInfoVo);
		if(flag > 0) {
			resultMap.put("success", true);
			resultMap.put("result","修改专辑内容成功!");
		} else {
			resultMap.put("success", true);
			resultMap.put("result","修改专辑内容失败!flag="+flag);
		}
		return resultMap;
	}
	@RequestMapping("/special/delete_special")
	@ResponseBody
	public Object deleteSpecial(int f_si_id){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = specialServiceBean.deleteSpecial(f_si_id);
		resultMap.put("resultTitle", "删除结果");
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","删除成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","删除失败!");
		}
		return resultMap;
	}

	@RequestMapping("/special/select_special")
	@ResponseBody
	public Object selectSpecial(String f_si_id){
		SpecialInfoVo specialInfoVo=specialServiceBean.selectSpecial(f_si_id);
		return specialInfoVo;
	}

	/**
	 * 查询活动列表
	 * @param map
	 * @param cmActivityVo
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("/special/special_list")
	@ResponseBody
	public Object specialList(ModelMap map, HttpSession session,SpecialInfoVo specialInfoVo,int page, int rows){
		PmsUserVo userVo = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		//父级组织id为0是根组织,有最高权限 否则必须使用组织本身id覆盖companyid,就看不到别的组织的内容了 
		if(userVo.getParentOrgId() > 0){
			specialInfoVo.setF_si_companyid(userVo.getOrgId());
		}
		Map<String,Object> specialListMap = new HashMap<String, Object>();
		specialListMap=specialServiceBean.specialList(specialInfoVo,page,rows);
		return specialListMap;
	}

	/**
	 * 上传图片
	 * @param request
	 * @param response
	 * @param session
	 * @throws Exception
	 */
	@RequestMapping("/special/specialUploadPictures")
	@ResponseBody
	public void activityUploadPictures(HttpServletRequest request ,HttpServletResponse response,HttpSession session) throws Exception {
		String picLeftFile = session.getServletContext().getInitParameter("img_path");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("uploadify");
		String uploadifyFileName = file.getOriginalFilename();
		String picType = request.getParameter("picType");
		picType = URLDecoder.decode(picType, "UTF-8");
		String filePath = specialServiceBean.getFilePath(picType);
		String fileName = specialServiceBean.getFileName(uploadifyFileName);
		if(fileCheck(picLeftFile + filePath,fileName)) {
		File picFile = new File(picLeftFile + filePath,fileName);
		if(!picFile.exists())
			picFile.mkdirs();
		try {
			file.transferTo(picFile);
			LOG.debug("上传图片成功！");
		} catch(Exception e) {
			e.printStackTrace();
			LOG.error("上传图片失败！",e);
		}
			FileInputStream resultStream = null;
		try {
			resultStream = new FileInputStream(picFile);
			BufferedImage img = ImageIO.read(resultStream);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			String jsonData = "{\"width\":\""+img.getWidth()+"\",\"height\":\""+img.getHeight()+"\",\"imgpath\":\""+filePath+fileName+"\"}";
			LOG.debug("uploadPicture-filePath+fileName:"+filePath+fileName+"--jsonData:"+jsonData);
			out.write(jsonData);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
				try {
					resultStream.close();
				} catch (IOException e) {
				}
			}
		}
	}

	@RequestMapping("/special/specialExcel")
	@ResponseBody
	public void specialExcel(SpecialInfoVo specialInfoVo,HttpServletResponse response) throws IOException {
		List<SysProductVo> sysProductList = specialServiceBean.selectSysProduct();
		List<SpecialInfoVo> list = specialServiceBean.selectSpecialListExcel(specialInfoVo);
		for (SpecialInfoVo specialInfoVo2 : list) {

			if ("1".equals(specialInfoVo2.getF_si_resolution())) {
				specialInfoVo2.setF_si_resolution("高清");
			}else {
				specialInfoVo2.setF_si_resolution("标清");
			}
			for (SysProductVo sysProductVo2 : sysProductList) {
				if (sysProductVo2.getF_sp_id()==specialInfoVo2.getF_si_productid()) {
					specialInfoVo2.setF_si_udate(sysProductVo2.getF_sp_name());
					break;
				}
			}
		}
		List<MyEntry<String, String>> excelCpHeader=new ArrayList<MyEntry<String, String>>();
		excelCpHeader.add(new MyEntry<String,String>("f_si_name","专辑名称"));
		excelCpHeader.add(new MyEntry<String,String>("f_si_resolution","分组"));
		excelCpHeader.add(new MyEntry<String,String>("f_si_startdate","上线时间"));
		excelCpHeader.add(new MyEntry<String,String>("f_si_enddate","下线时间"));
		excelCpHeader.add(new MyEntry<String,String>("f_si_udate","所属产品"));
		boolean flag=ExcelUtil.generateExcel(list, excelCpHeader, response);
	}
}
